package com.tjing.bussiness.controller;

import com.alibaba.fastjson.JSONObject;

import com.google.common.collect.Lists;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.tjing.bussiness.model.*;
import com.tjing.frame.controller.ToolController;
import com.tjing.frame.model.User;
import com.tjing.frame.object.RequestObject;
import com.tjing.frame.services.DbServices;
import com.tjing.frame.util.CodeHelper;
import com.tjing.frame.util.NetworkUtil;
import common.MatrixToImageWriter;
import common.tool;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by cwp on 2017/2/16.
 */
@Controller
@RequestMapping(value="/wechat/tool")
public class WechatToolController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private DbServices dbServices;

    private static org.apache.log4j.Logger logger= org.apache.log4j.Logger.getLogger(WechatToolController.class);

    public String nonceStr= getNoceStr();
    public String timestamp=String.valueOf(System.currentTimeMillis() / 1000);
    private static String baseUrl = "http://wx.54pai.cn/jingtong";

    @RequestMapping(value="/getWxConfig")
    public @ResponseBody JSONObject getWxConfig(HttpServletRequest request){
        JSONObject param = CodeHelper.getRequestParams(request);
        JSONObject jobj = new JSONObject();
        jobj.put("timestamp", timestamp);
        jobj.put("nonceStr", nonceStr);
        jobj.put("signature", createSign(param.getString("url")));
        return jobj;
    }
    public String getNoceStr(){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for(int i = 1 ; i <= 16; ++i){
            int number = random.nextInt(62);//[0,62)

            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
    public String createSign(String url) {
        //获取token
        String token= WeixinUtil.getAccessToken(Constants.appId, Constants.appSecret).getToken();
        String js=WeixinUtil.getJsapiTicket(token).getTicket();
        String string1="jsapi_ticket="+js+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;

        return SHA1(string1);
    }
    /**
     * @date： 2015年12月17日 上午9:24:43
     * @description： SHA、SHA1加密
     * @parameter：   str：待加密字符串
     * @return：  加密串
     **/
    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 获取媒体文件
     * @paramaccessToken 接口访问凭证
     * @param mediaId 媒体文件id
     * @param savePath 文件在本地服务器上的存储路径
     * */
    public String downloadMedia(String mediaId, String savePath) {
        String accessToken = WeixinUtil.getAccessToken(Constants.appId, Constants.appSecret).getToken();
        String filePath = null;
        String fileExt=null;
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            if (!savePath.endsWith("/")) {
                savePath += "/";
            }
            // 根据内容类型获取扩展名
            fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
            // 将mediaId作为文件名
            filePath = savePath + mediaId + fileExt;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();

            conn.disconnect();
            String info = String.format("下载媒体文件成功，filePath=" + filePath);
            System.out.println(info);
        } catch (Exception e) {
            filePath = null;
            String error = String.format("下载媒体文件失败：%s", e);
            System.out.println(error);
        }

        StringBuffer url = request.getRequestURL();

        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getContextPath()).append("/").toString();
        return tempContextUrl+"wxupload/"+ mediaId + fileExt;
    }
    /**
     * 根据内容类型判断文件扩展名
     * @param contentType 内容类型
     * @return
     */
    public static String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }

    @RequestMapping(value="/uploadimg")
    public @ResponseBody String uploadimg(HttpServletRequest request){
        JSONObject param = CodeHelper.getRequestParams(request);
        String imgPath = request.getRealPath("/wxupload");

        //如果此文件夹不存在则创建一个
        File f = new File(imgPath);
        if(!f.exists()){
            f.mkdir();
        }
        String filePath=downloadMedia(param.getString("fileData"), imgPath);

        return filePath;
    }
    @RequestMapping("/userAuth")
    public String userAuth(HttpServletRequest request, HttpServletResponse response){
        try {
            String ODR_NO = request.getParameter("ODR_NO");
            String totalFee = request.getParameter("totalFee");
            System.out.println("in userAuth,ODR_NO:" + ODR_NO);

            //授权后要跳转的链接
            String backUri = baseUrl + "/weixin/wechat/tool/toPay";
            backUri = backUri + "?ODR_NO=" + ODR_NO+"&ODR_TARG_TYPE="+request.getParameter("ODR_TARG_TYPE")+"&totalFee="+totalFee;
            //URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
            backUri = URLEncoder.encode(backUri);
            //scope 参数视各自需求而定，这里用scope=snsapi_base 不弹出授权页面直接授权目的只获取统一支付接口的openid
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" + Constants.appId +
                    "&redirect_uri=" +
                    backUri+
                    "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            System.out.println("url:" + url);
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/toPay")
    public String toPay(HttpServletRequest request, HttpServletResponse response, Model model){
        try {
            HttpSession session = request.getSession();
            String orderId = ToolController.GetOrderId();
            System.out.println("in toPay,orderId:" + orderId);

            String totalFeeStr = request.getParameter("totalFee");
            Float totalFee = 0.0f;

            if(StringUtils.isNotBlank(totalFeeStr)){
                totalFee = new Float(totalFeeStr);
            }
            System.out.println("i44788");
            //网页授权后获取传递的参数
            String userId = request.getParameter("userId");
            String code = request.getParameter("code");
            //String code = session.getAttribute("code").toString();
//          System.out.println("code:111111111111111");
            System.out.println("code:"+code);
            System.out.println("userId:"+userId);

            //获取统一下单需要的openid
            //String openId =  session.getAttribute("openid").toString();
            String openId ="";
            String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + Constants.appId + "&secret=" + Constants.appSecret + "&code=" + code + "&grant_type=authorization_code";
            System.out.println("URL:"+URL);
            JSONObject jsonObject = tool.httpsRequest(URL, "GET", null);
            if (null != jsonObject) {
                openId = jsonObject.getString("openid");
                System.out.println("openId:" + openId);
            }

            //获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
            //随机数
            //String nonce_str = "1add1a30ac87aa2db72f57a2375d8fec";
            String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
            //商户订单号
            String out_trade_no = request.getParameter("ODR_NO");
            //商品描述
            String body = out_trade_no;

            //订单生成的机器 IP
            String spbill_create_ip = request.getRemoteAddr();
            //总金额
            //TODO
            Integer total_fee = Math.round(totalFee*100);
            //Integer total_fee = 1;

            //商户号
            //String mch_id = partner;
            //子商户号  非必输
            //String sub_mch_id="";
            //设备号   非必输
            //String device_info="";
            //附加数据
            //String attach = userId;
            //总金额以分为单位，不带小数点
            //int total_fee = intMoney;
            //订 单 生 成 时 间   非必输
            //String time_start ="";
            //订单失效时间      非必输
            //String time_expire = "";
            //商品标记   非必输
            //String goods_tag = "";
            //非必输
            //String product_id = "";

            //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
            String notify_url = baseUrl + "/weixin/wechat/tool/notifyUrl";

            SortedMap<String, String> packageParams = new TreeMap<String, String>();
            packageParams.put("appid", Constants.appId);
            packageParams.put("mch_id", Constants.partner);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("body", body);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("total_fee", total_fee+"");
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", notify_url);
            packageParams.put("trade_type", Constants.trade_type);
            packageParams.put("openid", openId);

            RequestHandler reqHandler = new RequestHandler(request, response);
            reqHandler.init(Constants.appId, Constants.appSecret, Constants.partnerkey);

            String sign = reqHandler.createSign(packageParams);
            System.out.println("sign:"+sign);
            String xml="<xml>"+
                    "<appid>"+Constants.appId+"</appid>"+
                    "<mch_id>"+Constants.partner+"</mch_id>"+
                    "<nonce_str>"+nonce_str+"</nonce_str>"+
                    "<sign>"+sign+"</sign>"+
                    "<body>"+body+"</body>"+
                    "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
                    "<total_fee>"+total_fee+""+"</total_fee>"+
                    "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
                    "<notify_url>"+notify_url+"</notify_url>"+
                    "<trade_type>"+Constants.trade_type+"</trade_type>"+
                    "<openid>"+openId+"</openid>"+
                    "</xml>";
            System.out.println("xml："+xml);

            String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String prepay_id="";
            try {
                prepay_id = WeixinPayUtil.getPayNo(createOrderURL, xml);
                System.out.println("prepay_id:" + prepay_id);
                if(prepay_id.equals("")){
                    request.setAttribute("ErrorMsg", "统一支付接口获取预支付订单出错");
                    //response.sendRedirect("error.jsp");
                    return "wechat/payment/error";
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            SortedMap<String, String> finalpackage = new TreeMap<String, String>();

            String packages = "prepay_id="+prepay_id;
            finalpackage.put("appId", Constants.appId);
            finalpackage.put("timeStamp", timestamp);
            finalpackage.put("nonceStr", nonce_str);
            finalpackage.put("package", packages);
            finalpackage.put("signType", Constants.signType);
            String finalsign = reqHandler.createSign(finalpackage);
            System.out.println("/jsapi?appid="+Constants.appId+"&timeStamp="+timestamp+"&nonceStr="+nonce_str+"&package="+packages+"&sign="+finalsign);

            model.addAttribute("appid", Constants.appId);
            model.addAttribute("timeStamp", timestamp);
            model.addAttribute("nonceStr", nonce_str);
            model.addAttribute("packageValue", packages);
            model.addAttribute("sign", finalsign);

            model.addAttribute("bizOrderId", orderId);
            model.addAttribute("orderId", orderId);
            model.addAttribute("payPrice", total_fee);
            model.addAttribute("ODR_NO", request.getParameter("ODR_NO"));
            model.addAttribute("ODR_TARG_TYPE", request.getParameter("ODR_TARG_TYPE"));
            return "wechat/payment/jsapi";
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 微信异步回调，不会跳转页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/notifyUrl")
    public String weixinReceive(HttpServletRequest request,HttpServletResponse response, Model model){
        System.out.println("==开始进入h5支付回调方法==");
        String xml_review_result = WeixinPayUtil.getXmlRequest(request);
        System.out.println("微信支付结果:"+xml_review_result);
        Map resultMap = null;
        try {
            resultMap = WeixinPayUtil.doXMLParse(xml_review_result);
            System.out.println("resultMap:" + resultMap);
            if(resultMap != null && resultMap.size() > 0){
                String sign_receive = (String)resultMap.get("sign");
                System.out.println("sign_receive:"+sign_receive);
                resultMap.remove("sign");
                String checkSign = WeixinPayUtil.getSign(resultMap,Constants.partnerkey);
                System.out.println("checkSign:" + checkSign);

                //签名校验成功
                if(checkSign != null && sign_receive != null &&
                        checkSign.equals(sign_receive.trim())){
                    System.out.println("weixin receive check Sign sucess");
                    try{
                        //获得返回结果
                        String return_code = (String)resultMap.get("return_code");

                        if("SUCCESS".equals(return_code)){
                            String out_trade_no = (String)resultMap.get("out_trade_no");
                            System.out.println("weixin pay sucess,out_trade_no:"+out_trade_no);
                            //处理支付成功以后的逻辑，这里是写入相关信息到文本文件里面，如果有订单的处理订单
                            try{
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String content = out_trade_no+"        "+sdf.format(new Date());
                                String fileUrl = System.getProperty("user.dir") + File.separator+"WebContent" + File.separator + "data" + File.separator + "order.txt";
                                TxtUtil.writeToTxt(content, fileUrl);
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }else{
                            model.addAttribute("payResult", "0");
                            model.addAttribute("err_code_des", "通信错误");
                        }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }else{
                    //签名校验失败
                    System.out.println("weixin receive check Sign fail");
                    String checkXml = "<xml><return_code><![CDATA[FAIL]]></return_code>"+
                            "<return_msg><![CDATA[check sign fail]]></return_msg></xml>";
                    WeixinPayUtil.getTradeOrder("http://weixin.xinfor.com/wx/notifyUrl", checkXml);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 页面js返回支付成功后，查询微信后台是否支付成功，然后跳转结果页面
     * @param request
     * @param response
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/success")
    public String toWXPaySuccess(HttpServletRequest request,
                                 HttpServletResponse response, Model model) throws IOException{
        String id = request.getParameter("orderId");
        System.out.println("toWXPaySuccess, orderId: " + id);
        try {
            Map resultMap = WeixinPayUtil.checkWxOrderPay(id);
            System.out.println("resultMap:" + resultMap);
            String return_code = (String)resultMap.get("return_code");
            String result_code = (String)resultMap.get("result_code");
            System.out.println("return_code:" + return_code + ",result_code:" + result_code);
            if("SUCCESS".equals(return_code)){
                if("SUCCESS".equals(result_code)){
                    model.addAttribute("orderId", id);
                    model.addAttribute("payResult", "1");
                }else{
                    String err_code = (String)resultMap.get("err_code");
                    String err_code_des = (String)resultMap.get("err_code_des");
                    System.out.println("weixin resultCode:"+result_code+",err_code:"+err_code+",err_code_des:"+err_code_des);

                    model.addAttribute("err_code", err_code);
                    model.addAttribute("err_code_des", err_code_des);
                    model.addAttribute("payResult", "0");
                }
            }else{
                model.addAttribute("payResult", "0");
                model.addAttribute("err_code_des", "通信错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "wechat/parent/order_list";
    }

    @RequestMapping(value="/getAdvModel")
    public @ResponseBody List getAdvModel(RequestObject requestObject,HttpServletResponse response) throws Exception{
        String callback = request.getParameter("callback");
        JSONObject param = CodeHelper.getRequestParams(request);
        List<TaxAdv> taxAdvs = dbServices.findList("TaxAdv","{id:'"+  param.getString("id") + "'}","");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(taxAdvs);
        String json="";
        int i=0;

        for(TaxAdv ut:taxAdvs){
            if(i!=0){
                json+=",";
            }
            String advContent=ut.getAdvContent();
            advContent=advContent.replaceAll(" ", "%20");
            advContent=tool.getURLEncoderString(advContent);
            json+="{\"type\":\""+ut.getType()+"\",\"advContent\":'"+advContent+"',\"picUrl\":\""+ut.getPicUrl()+"\",\"advHeight\":\""+ut.getAdvHeight()+"\",\"linkUrl\":\""+ut.getLinkUrl()+"\",\"isClose\":\""+ut.getIsClose()+"\"}";

            i++;
        }
        if(param.getString("type")!=null&&param.getString("type").equals("1")){
            out.print(json);
        }
        else {
            out.print(callback + "(" + json + ")");
        }
        return null;

    }

    @RequestMapping(value="/addTaxAccessLog")
    public @ResponseBody void addTaxAccessLog(RequestObject requestObject) throws Exception{
        JSONObject param = CodeHelper.getRequestParams(request);
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);
        List<JSONObject> jsonAccessLog = Lists.newArrayList();
        JSONObject jobAccessLog = new JSONObject();
        jobAccessLog.put("ip", request.getRemoteAddr());
        jobAccessLog.put("device", common.tool.getURLDecoderString(param.getString("device")));
        jobAccessLog.put("createDateTime", strnowTime);
        jobAccessLog.put("modifDatetime", strnowTime);
        jsonAccessLog.add(jobAccessLog);
        dbServices.saveOrupdateRecords("TaxAccessLog", jsonAccessLog, null, false);
    }
    //阅读
    @RequestMapping("/read")
    public @ResponseBody Map read(HttpServletRequest request,HttpServletResponse response) {

        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);
        JSONObject param = CodeHelper.getRequestParams(request);
        Integer taskId=param.getInteger("taskid");
        String DeviceType=param.getString("DeviceType");
        String OperSys=param.getString("OperSys");
        String inviter=param.getString("inviter");
        String openId=param.getString("openId");
        String from=param.getString("from");
        Integer iscontinue=param.getInteger("iscontinue");
        String srcIp= null;
        try {
            srcIp = NetworkUtil.getIpAddress(request);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HashMap<Integer, Object> intParamMap = new HashMap();
        String hql="";
        Integer i=0;
        intParamMap.clear();
        intParamMap.put(i++, inviter);
        hql="from QhUser where uid=?";
        List<QhUser> qhUsers = dbServices.findListByHql(hql, intParamMap);
        QhUser qhUser = dbServices.getEntity(QhUser.class, qhUsers.get(0).getId());

        String deviceId=CodeHelper.getCookie(request, "deviceId");
        if(deviceId==null||deviceId==""){
            deviceId=CodeHelper.setCookie(response, "deviceId");
        }

        QhTask qhTask=dbServices.getEntity(QhTask.class,taskId);

        JSONObject returnJob = new JSONObject();

        //如果是继续分享，判断广告主余额是否足以扣费
        if(iscontinue==1){
            User user=dbServices.getEntity(User.class,qhTask.getCreateUser());
            if(user.getAvailFund()<qhTask.getAdvPrice()){
                returnJob.put("data", 0);
                returnJob.put("url", qhTask.getAdvLink());
                return returnJob;
            }
        }

        i=0;
        intParamMap.clear();
        intParamMap.put(i++, taskId);
        intParamMap.put(i++, srcIp);
        hql="from QhTaskRead where taskId=? and srcIp=?";
        List reads = dbServices.findListByHql(hql, intParamMap);
        if(reads.size()>0){
            returnJob.put("data", 0);
            returnJob.put("url", qhTask.getAdvLink());
            return returnJob;
        }

        List<JSONObject> taskReads = Lists.newArrayList();
        JSONObject jobj = new JSONObject();
        jobj.put("taskId", taskId);
        jobj.put("uid", qhUser.getMobile());
        jobj.put("srcIp",srcIp);
        jobj.put("deviceType",DeviceType);
        jobj.put("deviceId",deviceId);
        jobj.put("tlService","");
        jobj.put("operSys",OperSys);
        jobj.put("openId","");
        jobj.put("wechatNum","");
        jobj.put("shareType",from);
        jobj.put("createUser", openId);
        jobj.put("createDateTime",strnowTime);
        jobj.put("modifyUser", openId);
        jobj.put("modifyDateTime", strnowTime);
        jobj.put("state", 99);
        taskReads.add(jobj);
        dbServices.saveOrupdateRecords("QhTaskRead", taskReads, null, false);

        i=0;
        intParamMap.clear();
        intParamMap.put(i++, taskId);
        intParamMap.put(i++, qhUser.getMobile());
        hql="from QhTaskRead where taskId=? and uid=?";
        reads = dbServices.findListByHql(hql, intParamMap);

        /*hql="select * from qh_task_read where taskId=? and uid=? and LOCATE('iOS', opersys)>0";
        List sysreads = dbServices.findListBySql(hql, intParamMap);

        if(from.equals("QQ")&&sysreads.size()>0&&reads.size()==1){
            returnJob.put("data", 0);
            returnJob.put("url", qhTask.getAdvLink());
            return returnJob;
        }*/
        i = 0;
        intParamMap.clear();
        intParamMap.put(i++, taskId);
        intParamMap.put(i++, qhUser.getMobile());
        hql = "select sum(CashMoney) from qh_user_profit where TaskId=? and CreateUser=? and (type='分享' or type='阅读')";
        Object Oprofit = dbServices.findUniqueBySql(hql, intParamMap);
        Double profit = 0.0;
        if (Oprofit != null) {
            profit = Double.valueOf(Oprofit.toString());
        }

        i = 0;
        intParamMap.clear();
        intParamMap.put(i++, taskId);
        intParamMap.put(i++, qhUser.getMobile());
        hql="from QhTaskShare where taskid=? and createuser=? and iscontinue=0";
        List<QhTaskShare> qhTaskShares=dbServices.findListByHql(hql,intParamMap);
        if(qhTaskShares.size()>0) {
            //添加分享收益
            if (qhTaskShares.get(0).getCreateUserLeave()!=1&&qhTask.getRealCommission() >= profit + qhTask.getShareProfit()) {
                if (from.equals("QQ")) {
                    if(reads.size() == 2) {
                        addProfit(taskId, "分享", qhTask.getShareProfit(), qhUser.getId(), qhUser.getMobile());
                    }
                } else {
                    if(reads.size() == 1) {
                        addProfit(taskId, "分享", qhTask.getShareProfit(), qhUser.getId(), qhUser.getMobile());
                    }
                }
            }
        }

        if (qhTask.getRealCommission() >= profit + qhTask.getReadProfit()) {
            if (from.equals("QQ")) {
                if (reads.size() > 1) {
                    //添加阅读收益
                    addProfit(taskId, "阅读", qhTask.getReadProfit(), qhUser.getId(), qhUser.getMobile());
                    //继续分享扣费
                    if(iscontinue==1) {
                        addCharg(taskId, qhUser.getMobile());
                    }
                }
            } else {
                //添加阅读收益
                addProfit(taskId, "阅读", qhTask.getReadProfit(), qhUser.getId(), qhUser.getMobile());
                //继续分享扣费
                if(iscontinue==1) {
                    addCharg(taskId, qhUser.getMobile());
                }
            }
        }
        //完成奖励任务
        //comRewardTask_read(qhUser.getId());
        returnJob.put("data", 1);
        returnJob.put("url", qhTask.getAdvLink());
        return returnJob;
    }

    //阅读消息
    @RequestMapping("/readnotice")
    public @ResponseBody String readnotice(HttpServletRequest request) {
        JSONObject param = CodeHelper.getRequestParams(request);
        Integer id = param.getInteger("id");
        QhNotice qhNotice=dbServices.getEntity(QhNotice.class,id);
        qhNotice.setState(1);
        dbServices.update(qhNotice);

        return "1";
    }

    //阅读新手课程
    @RequestMapping("/readCourse")
    public @ResponseBody String readCourse(HttpServletRequest request) {
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);

        JSONObject param = CodeHelper.getRequestParams(request);
        Integer uid = param.getInteger("uid");

        HashMap<Integer, Object> intParamMap = new HashMap();
        Integer i=0;

        i=0;
        intParamMap.clear();
        intParamMap.put(i++, uid);
        Object Ocnt=dbServices.findUniqueBySql("select count(0) from qh_user_task_centre where pid=1 and createuser=?", intParamMap);

        if(Integer.valueOf(Ocnt.toString())==0) {
            QhTaskCentre qhTaskCentre=dbServices.getEntity(QhTaskCentre.class,1);
            QhUser qhUser=dbServices.getEntity(QhUser.class,uid);

            List<JSONObject> jsonObjects = Lists.newArrayList();
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("pid", 1);
            jsonObject.put("createUser", uid);
            jsonObject.put("createDateTime", strnowTime);
            jsonObject.put("modifyUser", uid);
            jsonObject.put("modifyDateTime", strnowTime);
            jsonObject.put("state", 99);
            jsonObjects.add(jsonObject);
            String returnId=dbServices.saveOrupdateRecords("QhUserTaskCentre", jsonObjects, null, false);

            addProfit(Integer.valueOf(returnId), "认识钱狐", qhTaskCentre.getCashMoney(), qhUser.getId(), qhUser.getMobile());
        }

        return "1";
    }

    public void comRewardTask_read(Integer uid) {
        QhUser qhUser = dbServices.getEntity(QhUser.class, uid);
        String mobile = qhUser.getMobile();

        Integer i=0;
        HashMap<Integer, Object> intParamMap = new HashMap();
        String hql="";
        i=0;
        intParamMap.clear();
        intParamMap.put(i++, mobile);
        hql="select count(0) from qh_task_read where uid=?";

        Integer ReadCntByUid=0;
        Object OreadCntByUid=dbServices.findUniqueBySql(hql, intParamMap);
        ReadCntByUid=Integer.parseInt(OreadCntByUid.toString());

        hql="from QhUserToolCash where type='阅读' and createuser=?";
        List<QhUserToolCash> qhUserToolCashs = dbServices.findListByHql(hql, intParamMap);
        if(qhUserToolCashs.size()>0){
            if(qhUserToolCashs.get(0).getNumber()==ReadCntByUid){
                QhUserToolCash qhUserToolCash=dbServices.getEntity(QhUserToolCash.class,qhUserToolCashs.get(0).getId());
                qhUserToolCash.setState(1);
                dbServices.update(qhUserToolCash);

                if(qhUserToolCashs.get(0).getRewardType().equals("金额")){
                    addProfit(qhUserToolCashs.get(0).getId(),"奖励",qhUserToolCashs.get(0).getCashMoney(), qhUser.getId(),mobile);
                }
            }
        }
    }

    private void addCharg(Integer taskId,String mobile){
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);
        QhTask qhTask=dbServices.getEntity(QhTask.class,taskId);
        List<JSONObject> jsonObjects = Lists.newArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", qhTask.getCreateUser());
        jsonObject.put("taskId", qhTask.getId());
        jsonObject.put("cashMoney", qhTask.getAdvPrice());
        jsonObject.put("note", qhTask.getAdvLink());
        jsonObject.put("createUser", mobile);
        jsonObject.put("createDateTime", strnowTime);
        jsonObject.put("modifyUser", mobile);
        jsonObject.put("modifyDateTime", strnowTime);
        jsonObject.put("state", 99);
        jsonObjects.add(jsonObject);
        dbServices.saveOrupdateRecords("QhCharg", jsonObjects, null, false);

        //修改广告主的总资金和余额
        User user=dbServices.getEntity(User.class,qhTask.getCreateUser());
        double TotalFund=user.getTotalFund() - qhTask.getAdvPrice();
        double AvailFund=user.getAvailFund() - qhTask.getAdvPrice();
        user.setTotalFund(TotalFund);
        user.setAvailFund(AvailFund);
        dbServices.update(user);
    }

    private void addProfit(Integer taskId,String type,Double cashMoney,Integer id,String mobile){
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);

        List<JSONObject> jsonQhUserProfit = Lists.newArrayList();
        JSONObject jobQhUserProfit = new JSONObject();
        jobQhUserProfit.put("taskId", taskId);
        jobQhUserProfit.put("type", type);
        jobQhUserProfit.put("cashMoney", cashMoney);
        jobQhUserProfit.put("note", "获得"+type+"收益" + cashMoney+ "元");
        jobQhUserProfit.put("createUser", mobile);
        jobQhUserProfit.put("createDateTime", strnowTime);
        jobQhUserProfit.put("modifyUser", mobile);
        jobQhUserProfit.put("modifyDateTime", strnowTime);
        jobQhUserProfit.put("state", 99);
        jsonQhUserProfit.add(jobQhUserProfit);
        dbServices.saveOrupdateRecords("QhUserProfit", jsonQhUserProfit, null, false);

        //给分享人账户增加收益
        QhUser qhUser=dbServices.getEntity(QhUser.class,id);
        double TotalFund = qhUser.getTotalFund() + cashMoney;
        double AvailFund = qhUser.getAvailFund() + cashMoney;
        qhUser.setTotalFund(TotalFund);
        qhUser.setAvailFund(AvailFund);
        dbServices.update(qhUser);

        List<JSONObject> jsonNotices = Lists.newArrayList();
        JSONObject jsonNotice = new JSONObject();
        jsonNotice.put("uid", id);
        jsonNotice.put("userType", "a");
        jsonNotice.put("type", "收益");
        jsonNotice.put("title", "获得"+type+"收益" + cashMoney+ "元");
        jsonNotice.put("note", "获得"+type+"收益" + cashMoney+ "元");
        jsonNotice.put("createUser", 1);
        jsonNotice.put("createDateTime", strnowTime);
        jsonNotice.put("modifyUser", 1);
        jsonNotice.put("modifyDateTime", strnowTime);
        jsonNotice.put("state", 99);
        jsonNotices.add(jsonNotice);
        dbServices.saveOrupdateRecords("QhNotice", jsonNotices, null, false);

        //极光推送
        ToolController.sendMsg("获得"+type+"收益" + cashMoney+ "元", mobile);

    }

    //获取基础参数
    @RequestMapping("/getSysPar")
    public @ResponseBody Object getSysPar(HttpServletRequest request) {
        QhSysPar qhSysPar=dbServices.getEntity(QhSysPar.class,1);

        return qhSysPar;
    }

    @RequestMapping("/getQRcode")
    public void getQRcode(String picurl,String url,HttpServletRequest request, HttpServletResponse response, Integer width, Integer height ) {
        try {

            int iWidth = (width == null?200: width);
            int iHeight = (height==null?200: height);

            MatrixToImageWriter.createRqCode(picurl,url, request,iWidth, iHeight, response.getOutputStream());

        } catch (Exception e) {

        }
    }

    @RequestMapping("/getCashQRcode")
    public void getCashQRcode(String picurl,String url,HttpServletRequest request, HttpServletResponse response, Integer width, Integer height ) {
        try {
            int iWidth = (width == null?150: width);
            int iHeight = (height==null?150: height);

            MatrixToImageWriter.createCashRqCode(picurl, url, request, iWidth, iHeight, response.getOutputStream());

        } catch (Exception e) {

        }
    }

    //获取试玩赚钱
    @RequestMapping("/getDemoList")
    public @ResponseBody List getDemoList(HttpServletRequest request) {
        JSONObject param = CodeHelper.getRequestParams(request);

        Integer i=0;
        HashMap<Integer, Object> intParamMap = new HashMap();

        String hql="from QhDemo";

        List<QhDemo> qhDemos = dbServices.findListByHql(hql, intParamMap);

        return qhDemos;
    }

    @RequestMapping("/DemoDownLoad")
    public @ResponseBody String DemoDownLoad(HttpServletRequest request) {
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);

        JSONObject param = CodeHelper.getRequestParams(request);
        QhSysPar qhSysPar=dbServices.getEntity(QhSysPar.class, 1);

        double cashMoney=param.getDouble("cashMoney")*qhSysPar.getDownloadPer();
        Integer id=param.getInteger("id");
        Integer uid=param.getInteger("uid");

        QhUser qhUser=dbServices.getEntity(QhUser.class, uid);
        String mobile=qhUser.getMobile();

        Integer i=0;
        HashMap<Integer, Object> intParamMap = new HashMap();
        intParamMap.put(i++, id);
        intParamMap.put(i++, mobile);
        String hql="from QhUserProfit where type='下载' and taskId=? and createUser=?";
        List<QhUserProfit> qhUserProfits=dbServices.findListByHql(hql,intParamMap);
        if(qhUserProfits.size()>0){
            return "0";
        }

        double TotalFund=qhUser.getTotalFund() + cashMoney;
        double AvailFund=qhUser.getAvailFund() + cashMoney;
        qhUser.setTotalFund(TotalFund);
        qhUser.setAvailFund(AvailFund);
        dbServices.update(qhUser);

        QhDemo qhDemo=dbServices.getEntity(QhDemo.class,id);

        List<JSONObject> jsonObjects = Lists.newArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", uid);
        jsonObject.put("userType", "a");
        jsonObject.put("type", "收益");
        jsonObject.put("title", "您下载了"+qhDemo.getName()+"，获得下载收益"+cashMoney+"元");
        jsonObject.put("note", "您下载了"+qhDemo.getName()+"，获得下载收益"+cashMoney+"元");
        jsonObject.put("createUser", 0);
        jsonObject.put("createDateTime", strnowTime);
        jsonObject.put("modifyUser", 0);
        jsonObject.put("modifyDateTime", strnowTime);
        jsonObject.put("state", 99);
        jsonObjects.add(jsonObject);
        dbServices.saveOrupdateRecords("QhNotice", jsonObjects, null, false);

        jsonObject.clear();
        jsonObjects.clear();
        jsonObject.put("taskId", id);
        jsonObject.put("type", "下载");
        jsonObject.put("cashMoney", cashMoney);
        jsonObject.put("note", "");
        jsonObject.put("createUser", mobile);
        jsonObject.put("createDateTime", strnowTime);
        jsonObject.put("modifyUser", mobile);
        jsonObject.put("modifyDateTime", strnowTime);
        jsonObject.put("state", 99);
        jsonObjects.add(jsonObject);
        dbServices.saveOrupdateRecords("QhUserProfit", jsonObjects, null, false);

        //极光推送
        ToolController.sendMsg("您下载了"+qhDemo.getName()+"，获得下载收益"+cashMoney+"元", mobile);

        return "1";
    }
    @RequestMapping("/getUser")
    public @ResponseBody Object getUser(HttpServletRequest request) {
        JSONObject param = CodeHelper.getRequestParams(request);
        Integer uid = param.getInteger("uid");
        QhUser qhUser=dbServices.getEntity(QhUser.class,uid);
        return qhUser;
    }
    @RequestMapping("/addDownLog")
    public void addDownLog(HttpServletRequest request) {
        Date nowTime=new Date();
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strnowTime= time.format(nowTime);

        List<JSONObject> jsonQhUserOperLog = Lists.newArrayList();
        JSONObject jobQhUserOperLog = new JSONObject();
        jobQhUserOperLog.put("name", "");
        jobQhUserOperLog.put("oid", "");
        jobQhUserOperLog.put("funName", "下载");
        jobQhUserOperLog.put("funPar", "");
        jobQhUserOperLog.put("optName", "");
        jobQhUserOperLog.put("srcIp", request.getRemoteAddr());
        jobQhUserOperLog.put("address", "");
        jobQhUserOperLog.put("note", "");
        jobQhUserOperLog.put("inviteeLeave", "");
        jobQhUserOperLog.put("srcPla", "qf_13");
        jobQhUserOperLog.put("createUserLeave", "");
        jobQhUserOperLog.put("createUser", "");
        jobQhUserOperLog.put("createDateTime", strnowTime);
        jobQhUserOperLog.put("modifyUser", "");
        jobQhUserOperLog.put("modifyDateTime", strnowTime);
        jobQhUserOperLog.put("state", 99);
        jsonQhUserOperLog.add(jobQhUserOperLog);
        dbServices.saveOrupdateRecords("QhUserOperLog", jsonQhUserOperLog, null, false);
    }

    /*@RequestMapping("/qr-code")
    public void placeQrOrder(String url,HttpServletResponse resp, Integer width, Integer height) throws Exception{
        resp.setHeader("Cache-Control", "no-store");
        resp.setHeader("Pragma", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/png");

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);

        BitMatrix bitMatrix = new MultiFormatWriter().encode("http://www.baidu.com", BarcodeFormat.QR_CODE, 300, 300, hints);
        BufferedImage image=MatrixToImageWriter.toBufferedImage(bitMatrix);
        MatrixToImageWriter.writeToStream(image, "png", resp.getOutputStream());
    }*/

}
